<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class UserAroCacheComponent extends Component
{

    public $_cache_config = 'user_aros';
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 获取用户组权限
     * @param  $id    aro_id
     * @param  $attr  属性
     *
     * @return 用户组权限
     */
    public function getVal($id, $attr = null)
    {
        if($id === null) {
            return null;
        }
        $key = 'user_aros-' . $id;
        $data = Cache::read($key,$this->_cache_config);
        if ($data === false) {
            $this->createCache($id);
            $data = Cache::read($key,$this->_cache_config);
        }

        if (empty($data)) {
            return null;
        }

        if ($data['enabled'] == 0) {
            return null;
        }

        if (empty($attr)) {
            return $data;
        }

        return $data[$attr];

    }

    /**
     * 创建用户组权限缓存
     * @param  $id  用户组id
     */
    public function createCache($id)
    {
        $key = 'user_aros-' . $id;
        $controller = $this->_registry->getController();
        $controller->loadModel('UserAros');

        $data = $controller->UserAros->find()
            ->where(['id' => $id])
            ->first();

        if (empty($data) || ($data['enabled'] == 0)) {
            Cache::write($key, null, $this->_cache_config);
        } else {
            $data['allowed'] = $this->_getAcos($data['allowed']);
            $data['denied'] = $this->_getAcos($data['denied']);

            Cache::write($key, $data, $this->_cache_config);
        }
    }

    /**
     * 创建所有用户组权限缓存
     */
    public function createAllCache()
    {
        $controller = $this->_registry->getController();
        $controller->loadModel('UserAros');
        $data = $controller->UserAros->find()
            ->select(['id'])
            ->toArray();
        foreach($data as $k=>$v) {
            $this->createCache($v['id']);
        }
    }

    private function _getAcos($ids)
    {
        $ids = json_decode($ids, true);
        if(empty($ids)){
            return [];
        }
        $controller = $this->_registry->getController();
        $controller->loadModel('UserAcos');

        $dataAuth = $controller->UserAcos->find()
            ->select(['memo', 'status'])
            ->where(['id IN' => $ids])
            ->toArray();

        $acos = [];
        foreach ($dataAuth as $k => $v){
            if($v['status'] <> 'enabled') {
                continue;
            }
            $arr = json_decode($v['memo'], true);

            $acos = array_merge_recursive($acos, $arr);

        }

        foreach($acos as $k=>$v) {
            $acos[$k] = array_unique($v);
        }

        return $acos;
    }

}